# -*- coding: UTF-8 -*-
# Author: Liang Bing
# Date Time: 2025/6/21 13:31
import subprocess
from pathlib import Path
from typing import Union
import textwrap


def run_or_die(
    cmd: Union[str, list],
    sh_file: Union[str, Path],
    log_file: Union[str, Path, None] = None
) -> None:
    """
    写入 shell 脚本并执行，失败时报错。
    - cmd: 要执行的命令（str 或 list）
    - sh_file: 要写入的 shell 文件路径
    - log_file: 日志输出路径（可选；若为 None 则仅打印控制台）
    """
    sh_path = Path(sh_file).absolute()
    sh_path.parent.mkdir(parents=True, exist_ok=True)

    script_text = cmd if isinstance(cmd, str) else " ".join(cmd)
    sh_path.write_text(textwrap.dedent(script_text), encoding="utf-8")
    sh_path.chmod(0o755)

    try:
        if log_file:
            log_path = Path(log_file).absolute()
            log_path.parent.mkdir(parents=True, exist_ok=True)
            with log_path.open("w", encoding="utf-8") as fp:
                subprocess.run([str(sh_path)], check=True, stdout=fp, stderr=fp, text=True)
        else:
            subprocess.run([str(sh_path)], check=True, text=True)
    except subprocess.CalledProcessError as e:
        raise e
    except Exception as err:
        raise err
